package com.xhh.nphm.web.controller.system;

import com.xhh.nphm.common.config.NphmConfig;
import com.xhh.nphm.common.constant.Constants;
import com.xhh.nphm.common.constant.ShiroConstants;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysMenu;
import com.xhh.nphm.common.core.domain.entity.SysRole;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.PageDomain;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.core.page.TableSupport;
import com.xhh.nphm.common.core.text.Convert;
import com.xhh.nphm.common.utils.*;
import com.xhh.nphm.framework.shiro.service.SysPasswordService;
import com.xhh.nphm.system.domain.Saffiche;
import com.xhh.nphm.system.mapper.SysRoleMapper;
import com.xhh.nphm.system.service.*;
import com.xhh.nphm.system.service.impl.CommonServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 首页 业务处理
 *
 * @author ydq
 */
@Controller
public class SysIndexController extends BaseController {
    @Autowired
    private ISysMenuService menuService;
    @Autowired
    private ISysConfigService configService;
    @Autowired
    private SysPasswordService passwordService;
    @Autowired
    private ICommonService commonService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private IWorkFormBaseService workFormBaseService;
    @Autowired
    private MwfSendBackService mwfSendBackService;
    @Autowired
    private SafficheService safficheService;
    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    private IsGoBackConfService isGoBackConfService;

    @GetMapping("/clear")
    public String clear(ModelMap mmap) {
        CommonServiceImpl.clearCatch();
        return index(mmap);
    }

    // 系统首页
    @GetMapping("/index")
    public String index(ModelMap mmap) {
        // 取身份信息
        SysUser user = getSysUser();
        // 根据用户id取出菜单
        List<SysMenu> menus = menuService.selectMenusByUser(user);
        //如果用户的部门为高新区，则为用户增加一个菜单 自由分类管理（61336）
        // if("高新区".equals(user.getDeptName())){
            //一级菜单 内容管理
            //SysMenu sysMenu1 = menuService.selectMenuById(21302l);
            //二级菜单 自由分类管理
            // SysMenu sysMenu2 = menuService.selectMenuById(61336l);
            // if(sysMenu2 != null){
            //     menus.add(sysMenu2);
            // }
//            List<SysMenu> childSysMenu=new ArrayList<SysMenu>();
//            childSysMenu.add(sysMenu2);
//            sysMenu1.setChildren(childSysMenu);
//            menus.add(sysMenu1);
//         }
        mmap.put("menus", menus);
        mmap.put("user", user);
        mmap.put("sideTheme", configService.selectConfigByKey("sys.index.sideTheme"));
        mmap.put("skinName", configService.selectConfigByKey("sys.index.skinName"));
        mmap.put("ignoreFooter", configService.selectConfigByKey("sys.index.ignoreFooter"));
        mmap.put("copyrightYear", NphmConfig.getCopyrightYear());
        mmap.put("isDefaultModifyPwd", initPasswordIsModify(user.getPwdUpdateDate()));
        mmap.put("isPasswordExpired", passwordIsExpiration(user.getPwdUpdateDate()));
        mmap.put("isMobile", ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")));
        // 缓存当前部门是否允许退回
        // CacheUtils.put(Constants.USER_CACHE_KEY,Constants.IS_GOBACK + user.getDeptId(), isGoBackConfService.checkPeerDeptIsGoBack(user.getDeptId()));
        // 菜单导航显示风格
        String menuStyle = configService.selectConfigByKey("sys.index.menuStyle");
        // 移动端，默认使左侧导航菜单，否则取默认配置
        String indexStyle = ServletUtils.checkAgentIsMobile(ServletUtils.getRequest().getHeader("User-Agent")) ? "index" : menuStyle;

        // 优先Cookie配置导航菜单
        Cookie[] cookies = ServletUtils.getRequest().getCookies();
        for (Cookie cookie : cookies) {
            if (StringUtils.isNotEmpty(cookie.getName()) && "nav-style".equalsIgnoreCase(cookie.getName())) {
                indexStyle = cookie.getValue();
                break;
            }
        }
        String webIndex="";
        if("呼叫中心".equals(user.getSortName())){
            webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        }else{
            webIndex="index-none";
        }
        //String webIndex = "topnav".equalsIgnoreCase(indexStyle) ? "index-topnav" : "index";
        return webIndex;
    }

    // 锁定屏幕
    @GetMapping("/lockscreen")
    public String lockscreen(ModelMap mmap) {
        mmap.put("user", getSysUser());
        ServletUtils.getSession().setAttribute(ShiroConstants.LOCK_SCREEN, true);
        return "lock";
    }

    // 解锁屏幕
    @PostMapping("/unlockscreen")
    @ResponseBody
    public AjaxResult unlockscreen(String password) {
        SysUser user = getSysUser();
        if (StringUtils.isNull(user)) {
            return AjaxResult.error("服务器超时，请重新登陆");
        }
        if (passwordService.matches(user, password)) {
            ServletUtils.getSession().removeAttribute(ShiroConstants.LOCK_SCREEN);
            return AjaxResult.success();
        }
        return AjaxResult.error("密码不正确，请重新输入。");
    }

    // 切换主题
    @GetMapping("/system/switchSkin")
    public String switchSkin() {
        return "skin";
    }

    // 切换菜单
    @GetMapping("/system/menuStyle/{style}")
    public void menuStyle(@PathVariable String style, HttpServletResponse response) {
        CookieUtils.setCookie(response, "nav-style", style);
    }
    //公告分页
    public TableDataInfo affichePackage(List<Saffiche> afficheList){
        Integer pageNum = 1;
        Integer pageSize = 20;
        List<Saffiche> safficheList = new ArrayList<>();
        for (Saffiche affiche : afficheList) {
            if (!safficheList.contains(affiche)) {
                safficheList.add(affiche);
            }
        }
        int num = safficheList.size();
        safficheList = safficheList.stream().skip((pageNum-1) * pageSize).limit(pageSize).collect(Collectors.toList());
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setCode(0);
        dataInfo.setRows(safficheList);
        dataInfo.setTotal(num);
        return dataInfo;
    }

    //计算总数
    private Long calcTotal(TableDataInfo tableDataInfo, List<Saffiche> list, Integer pageSize){
        int num = list.size();
        long total = tableDataInfo.getTotal();
        if (total % pageSize ==0) {
            total =  num/pageSize;
        }else {
            total = (long) Math.floor((num/ pageSize) + 1);
        }
        return total;
    }
    // 系统介绍
    @GetMapping("/system/main")
    public String main(ModelMap mmap) {
        //保存路径地址
        String href = "main";
        mmap.put("version", NphmConfig.getVersion());
        SysUser user = getSysUser();
        SysRole sysRole = user.getRoles().get(0);
        if(sysRole == null){
            user.setRoles(sysRoleMapper.selectRolesByUserId(user.getUserId()));
        }
        // String roles = userService.selectUserRoleId(user.getUserId());
        mmap.put("user", user);
        mmap.put("shortcutFuns", userService.selectFun(user.getUserId()));
        mmap.put("roles", sysRole.getRoleId());
        mmap.put("deptId",user.getDeptId());
        //通知公告 ：公告分页
        Integer pageNum = 1;
        Integer pageSize = 20;
        List<Saffiche> sAffiches = new ArrayList<>();
        Map<String, List<Saffiche>> collect = new HashMap<>();
        if ("呼叫中心".equals(user.getSortName())) {
            sAffiches = safficheService.selectSafficheByRoles(sysRole.getRoleId().toString());
        }else {
            sAffiches = safficheService.selectSafficheByDeptIds(user.getDeptId().toString());
        }
        if (sAffiches != null && sAffiches.size() > 0) {
            collect = sAffiches.stream().collect(Collectors.groupingBy(Saffiche::getSortName));
            for (Map.Entry<String, List<Saffiche>> entry : collect.entrySet()) {
                if (entry.getKey().equals("紧急")) {
                    mmap.put("instancy", affichePackage(entry.getValue().stream().sorted(Comparator.comparing(Saffiche::getGroupIndex)).collect(Collectors.toList())));
                } else if (entry.getKey().equals("重要")) {
                    mmap.put("important", affichePackage(entry.getValue().stream().sorted(Comparator.comparing(Saffiche::getGroupIndex)).collect(Collectors.toList())));
                } else if (entry.getKey().equals("普通")) {
                    mmap.put("common", affichePackage(entry.getValue().stream().sorted(Comparator.comparing(Saffiche::getGroupIndex)).collect(Collectors.toList())));
                }
            }
        }
        //已读
        List<Saffiche> readAffiche = safficheService.getReadAffiche(user.getUserId());
        mmap.put("read",affichePackage(readAffiche));
        mmap.put("num",pageNum);
        //重要待办事项
        List<Map> waitList = commonService.psPgFstWait(sysRole.getRoleId().toString(),user.getDeptId().toString(),IS_GAOXIN());
        mmap.put("wait",waitList);
        //上级催办键
        Map<String, Object> supUrgeOrderNum = commonService.supUrgeOrder(user.getDeptId().toString());
        mmap.put("urge",supUrgeOrderNum);
        //待处理来电记录数据查询
//        mmap.put("listWaitNum", telGetDealService.listWait(user.getUserNo(), new TtelGetDealEty()).size());
//        //电话工单草稿 数据查询
//        mmap.put("draftListNum", workFormBaseService.findTwfDraftList(new TworkFormBaseEty()).size());
//        //被退回电话工单 数据查询
//        mmap.put("backFlowNum", workFormBaseService.backFlowJson(new TworkFormBaseEty()).size());
//        //待审办理结果 数据查询
//        mmap.put("replyWaitNum", workFormBaseService.replyWaitJson(new TworkFormBaseEty()).size());
        //二级部门（区县级）61885992
        if (!"304".equals(user.getDeptId().toString())
                && !"399".equals(user.getDeptId().toString())
                && !"100".equals(user.getDeptId().toString())
                && user.getDeptId().toString().length() % 3 == 0
                && user.getDeptId().toString().length() <= 6){
            //重要待办事项
            mmap.put("wait",waitList);
            //电话和信息本月实时满意度情况
//            val maps = workFormBaseService.psTelTotalHandleState(user.getRoles().get(0).getRoleId().toString(), user.getDeptId().toString());
//            mmap.put("menuName",maps.get(0).get("menuName"));
//            mmap.put("flatTel",maps);
//            mmap.put("flatMail",mwfSendBackService.psMailTotalHandleState(user.getRoles().get(0).getRoleId().toString(),user.getDeptId().toString()));
            //本部门用户在线情况
//            mmap.put("areaAllCount",sysUserLoginStateService.areaAllCount(user.getDeptId()));
//            mmap.put("areaOnlineCount",sysUserLoginStateService.areaOnlineCount(user.getDeptId()));
//            mmap.put("loginStates",sysUserLoginStateService.loginState(user.getDeptId()));
//            mmap.put("deptUser",sysUserLoginStateService.findDeptNameOrUserNum(user.getDeptId()));
            List<Saffiche> dept = findDeptNotice(user.getAreaNo(), user.getDeptId().toString(), user.getUserId(),null);
            TableDataInfo data = affichePackage(dept);
            mmap.put("total",calcTotal(data,dept,pageSize));
            mmap.put("notice",data);
            mmap.put("read",affichePackage(safficheService.getReadAffiche(user.getUserId())));
            mmap.put("num",pageNum);
            href = "main2";
        }
        //一级部门（市级网络理政办）
        return href;
    }

    //查询本级、下级部门公告
    private List<Saffiche> findDeptNotice(String areaNo, String deptId, Long userId, String content){
        List<String> allDept = commonService.findAllDept(areaNo, deptId);
        allDept.add("-1");
        return safficheService.queryDeptNotice(allDept, userId,content);
    }


    /**
     * @methodName: search
     * @description: 首页模糊查询
     * @Author LiuTao
     * @param
     * @updateTime 2022/7/25 10:22
     * @return java.lang.String
     * @throws
     **/
    @PostMapping ("/system/notice/search")
    public String search(ModelMap mmap,@RequestParam("content") String content) {
        String href = "main2";
        SysUser user = getSysUser();
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<Saffiche> urgentSafficheList = new ArrayList<>();
//        List<Saffiche> sAffiches = safficheService.getNotice(roles, content,getSysUser().getUserId());
        List<Saffiche> sAffiches = findDeptNotice(user.getAreaNo(),user.getDeptId().toString(),user.getUserId(),content);
        for (Saffiche saffich : sAffiches) {
            if (!urgentSafficheList.contains(saffich)) {
                startPage();
                urgentSafficheList.add(saffich);
            }
        }
        int num=urgentSafficheList.size();
        if(Math.floor((num/ pageSize) + 1)<=pageNum){
            pageNum=(num/ pageSize) + 1;
        }
        urgentSafficheList=urgentSafficheList.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(urgentSafficheList);
        rspData.setTotal(num);
        long total = rspData.getTotal();
        if (total % pageSize ==0) {
            total =  num/pageSize;
        }else {
            total = (long) Math.floor((num/ pageSize) + 1);
        }
        mmap.put("notice",rspData);
        mmap.put("num",pageNum);
        mmap.put("total",total);
        return href+"::search";
    }
    //加载更多
    public TableDataInfo loadMoreData(List<Saffiche> afficheList){
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        List<Saffiche> safficheList = new ArrayList<>();
        for (Saffiche affiche : afficheList) {
            if (!safficheList.contains(affiche)) {
                startPage();
                safficheList.add(affiche);
            }
        }
        int num = safficheList.size();
        if(Math.floor((num / pageSize) + 1)<=pageNum){
            pageNum=(num/ pageSize) + 1;
        }
        safficheList = safficheList.stream().skip((pageNum - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(0);
        rspData.setRows(safficheList);
        rspData.setTotal(num);
        return rspData;
    }

    //加载更多
    @PostMapping("/system/notice/loadMore")
    public String loadMore(ModelMap map,@RequestParam("content") String content) {
        String href = "main";
        SysUser user = getSysUser();
        String roles = userService.selectUserRoleId(user.getUserId());
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        map.put("instancy",null);
        map.put("important",null);
        map.put("common",null);
        map.put("read",null);
        TableDataInfo tableData = null;
        switch (content) {
            case "instancy":
                System.out.println("紧急公告分页");
                List<Saffiche> urgentAffiche = safficheService.getUrgentAffiche(roles, user.getUserId());
                tableData = loadMoreData( urgentAffiche);
                break;
            case "important":
                System.out.println("重要公告分页");
                List<Saffiche> importantAffiche = safficheService.getImportantAffiche(roles, user.getUserId());
                tableData = loadMoreData(importantAffiche);
                break;
            case "common":
                System.out.println("普通公告分页");
                List<Saffiche> commonAffiche = safficheService.getCommonAffiche(roles, user.getUserId());
                tableData = loadMoreData(commonAffiche);
                break;
            case "read":
                System.out.println("已读公告分页");
                List<Saffiche> readAffiche = safficheService.getReadAffiche(user.getUserId());
                tableData = loadMoreData(readAffiche);
                break;
        }
        if(tableData != null){
            long total = tableData.getTotal();
            int num = tableData.getRows().size();
            if (total % pageSize ==0) {
                total =  num/pageSize;
            }else {
                total = (long) Math.floor((num/ pageSize) + 1);
            }
            map.put(content,tableData);
            map.put("num",pageNum);
            map.put("total",total);
        }
        return href+"::search";
    }

    // 检查初始密码是否提醒修改
    public boolean initPasswordIsModify(Date pwdUpdateDate) {
        Integer initPasswordModify = Convert.toInt(configService.selectConfigByKey("sys.account.initPasswordModify"));
        return initPasswordModify != null && initPasswordModify == 1 && pwdUpdateDate == null;
    }

    // 检查密码是否过期
    public boolean passwordIsExpiration(Date pwdUpdateDate) {
        Integer passwordValidateDays = Convert.toInt(configService.selectConfigByKey("sys.account.passwordValidateDays"));
        if (passwordValidateDays != null && passwordValidateDays > 0) {
            if (StringUtils.isNull(pwdUpdateDate)) {
                // 如果从未修改过初始密码，直接提醒过期
                return true;
            }
            Date nowDate = DateUtils.getNowDate();
            return DateUtils.differentDaysByMillisecond(nowDate, pwdUpdateDate) > passwordValidateDays;
        }
        return false;
    }

    /**
     * 获取全区实时满意情况电话工单数据
     */
    @GetMapping("/system/flatTelJson")
    @ResponseBody
    public List<Map> flatTelJson(){
        SysUser user = getSysUser();
        return workFormBaseService.psTelTotalHandleState(user.getRoles().get(0).getRoleId().toString(),user.getDeptId().toString(),IS_GAOXIN());
    }

    /**
     * 获取全区实时满意情况信件工单数据
     */
    @GetMapping("/system/flatMailJson")
    @ResponseBody
    public List<Map> flatMailJson(){
        SysUser user = getSysUser();
        return mwfSendBackService.psMailTotalHandleState(user.getRoles().get(0).getRoleId().toString(),user.getDeptId().toString(),IS_GAOXIN());
    }

    @GetMapping("/example")
    public ModelAndView example(){
        return new ModelAndView("/example");
    }
}
